﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RubCard : MonoBehaviour
{

    public float Height = 10;

    public float Width = 10;

    public int SegmentX = 10;

    public int SegmentZ = 20;

    public float FlipRatio = 0.6f;

    public int RotationFrameCount = 10;

    public int SmoothFrameCount = 10;

    public int NumFadeInFrameCount = 10;

    public int RotationAngle = 90;

    public int SmoothRotationAngle = 90;

    public Material SmoothMat;

    public Material CuoPaiMat;

    public Material NumMat;

    public Texture Front;

    public Texture Back;

    public Texture Num;

    public Texture huase;

    public float NumSize;

    private MeshFilter meshFilter;

    private MeshRenderer meshRender;

    private RenderTexture cameraTexture;

    private Camera camera;

    private UICamera uicamera;

    public Material cuoMat;

    private Material smoothMat;

    private float curRatio = 0;

    private int frameCount = 0;

    private bool startFlipAnimating = false;

    private bool flipEnd = false;

    private List<MeshRenderer> numMeshRenderer;

    public List<GameObject> numAndhuase;

    void Start()
    {

        //CreateTwoNum("","","");
    }

    public void Init()
    {
        meshFilter = gameObject.AddComponent<MeshFilter>();
        meshRender = gameObject.AddComponent<MeshRenderer>();

        Mesh mesh = new Mesh();

        float dh = Height / SegmentZ;
        float dw = Width / SegmentX;
        Vector3 startPos = new Vector3(-Width * 0.5f, 0, Height * 0.5f);
        Vector3[] vertices = new Vector3[(SegmentZ + 1) * (SegmentX + 1)];

        int index = 0;

        for (int i = 0; i < SegmentX + 1; i++)
        {
            for (int j = 0; j < SegmentZ + 1; j++)
            {
                Vector3 v = new Vector3();
                v.x = startPos.x + i * dw;
                v.y = startPos.y;
                v.z = startPos.z + j * dh;
                vertices[index] = v;
                index++;
            }
        }

        Vector2[] uvs = new Vector2[(SegmentZ + 1) * (SegmentX + 1)];
        float du = 1.0f / SegmentX;
        float dv = 1.0f / SegmentZ;
        index = 0;
        for (int i = 0; i < SegmentX + 1; i++)
        {
            for (int j = 0; j < SegmentZ + 1; j++)
            {
                uvs[index] = new Vector2(i * du, j * dv);
                index++;
            }
        }

        int[] triangles = new int[SegmentX * SegmentZ * 6 * 2];
        index = 0;
        for (var i = 0; i < SegmentX; i++)
        {
            for (int j = 0; j < SegmentZ; j++)
            {
                int role = SegmentZ + 1;
                int self = j + i * role;
                int next = j + (i + 1) * role;

                triangles[index] = self;
                triangles[index + 1] = self + 1;
                triangles[index + 2] = next + 1;

                triangles[index + 3] = self;
                triangles[index + 4] = next + 1;
                triangles[index + 5] = next;

                triangles[index + 6] = next + 1;
                triangles[index + 7] = self;
                triangles[index + 8] = self + 1;

                triangles[index + 9] = next;
                triangles[index + 10] = self;
                triangles[index + 11] = next + 1;

                index += 12;
            }
        }

        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        meshFilter.mesh = mesh;

        cuoMat = new Material(CuoPaiMat);
        smoothMat = new Material(SmoothMat);

        cuoMat.SetTexture("_FrontTexure", Front);
        cuoMat.SetTexture("_BackTexure", Back);
        cuoMat.SetFloat("_CardWidth", Width);
        cuoMat.SetFloat("_CardHeight", Height);
        cuoMat.SetFloat("_Rotio", 0);
        cuoMat.SetFloat("_Rotation", 0);


        smoothMat.SetTexture("_FrontTexure", Front);
        smoothMat.SetTexture("_BackTexure", Back);
        smoothMat.SetFloat("_CardWidth", Width);
        smoothMat.SetFloat("_CardHeight", Height);
        smoothMat.SetFloat("_Rotation", 0);

        meshRender.material = cuoMat;

        numMeshRenderer = new List<MeshRenderer>();


        //GameObject cameraGo = new GameObject("CuoPaiCamera");
        //camera = cameraGo.AddComponent<Camera>();
        //camera.transform.SetParent(transform);
        //camera.transform.localPosition = new Vector3(0,15, Height);
        //camera.transform.localEulerAngles = new Vector3(90,0,0);
        //cameraTexture = RenderTexture.GetTemporary(Screen.height, Screen.width);
        //camera.targetTexture = cameraTexture;
        //camera.orthographic = false;
        //camera.orthographicSize = 9;
        //camera.depth = 10;
        ////rawImg.texture = cameraTexture;
        ////rawImg.transform.localEulerAngles = new Vector3(0, 0, 0);

        //uicamera = cameraGo.AddComponent<UICamera>();
        //uicamera.eventType = UICamera.EventType.UI_3D;
    }


    bool on_startType = true;

    public void OnStart()
    {
        if (on_startType) return;
        //Debug.LogError("##################### OnStart()");

        startFlipAnimating = false;
        flipEnd = false;

        frameCount = 0;
        smoothMat.SetFloat("_Rotation", 1);
        cuoMat.SetFloat("_Rotio", 0);
        meshRender.material = cuoMat;
        //foreach (MeshRenderer renderer in numMeshRenderer)
        //{
        //    renderer.material.SetFloat("_Alpha", 0);
        //}

        on_startType = true;
    }

    public void SetRatio(float ratio)
    {
        if (flipEnd)
        {
            return;
        }

        this.curRatio = ratio;
        //Debug.LogError("rotation66666666666666666--------------"+ ratio);
        cuoMat.SetFloat("_Rotio", curRatio);
        
    }

    public void SetAngle(float ratio)
    {
        cuoMat.SetFloat("_Angle", ratio);
   
    }



    public void TouchUp()
    {
        if (this.curRatio >= FlipRatio || this.curRatio <= - FlipRatio)
        {
            startFlipAnimating = true;
        }
        else
        {
            this.SetRatio(0);
        }
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.W))
        {
            startFlipAnimating = true;
        }

        if (startFlipAnimating)
        {
            if (frameCount <= RotationFrameCount)
            {
                float rotation = RotationAngle * (frameCount * 1.0f / RotationFrameCount ) * Mathf.Deg2Rad;
                //Debug.LogError("rotation111111111111111111"+ rotation);
                meshRender.material.SetFloat("_Rotation", -rotation);
            }
            else if(frameCount <= (RotationFrameCount + SmoothFrameCount))
            {
                float scale = (frameCount - RotationFrameCount) * 1.0f / this.SmoothFrameCount;
                meshRender.material = smoothMat;
                //Debug.LogError("rotation2222222222222222222");
                meshRender.material.SetFloat("_Rotation", Mathf.Clamp((1 - scale) * SmoothRotationAngle * Mathf.Deg2Rad,0.01f,1f));
            }
            else if (frameCount <= (RotationFrameCount + SmoothFrameCount + NumFadeInFrameCount))
            {
                flipEnd = true;
                on_startType = false;
                //foreach (MeshRenderer renderer in numMeshRenderer)
                //{
                //    //Debug.LogError("rotation3333333333333333333");
                //    float alpha = (frameCount - RotationFrameCount - SmoothFrameCount) * 1.0f /
                //             NumFadeInFrameCount;
                //    renderer.material.SetFloat("_Alpha",alpha);
                //}
            }
            else
            {
                //Debug.Log("rotation4444444444444444");
                startFlipAnimating = false;
            }
            //Debug.Log("rotation5555555555555");
            this.frameCount++;
        }
    }

    void OnDestroy()
    {
        RenderTexture.ReleaseTemporary(cameraTexture);
    }

    public void CreateTwoNum(string numName,string huaseName, string cardName, string bgName)
    {
        string tempName = cardName + "full";

        Texture2D texture = ResHelper.LordUnitySysTypeBySyn(cardName, this.gameObject, typeof(Texture2D)) as Texture2D; 
        cuoMat.SetTexture("_BackTexure", texture);

        texture = ResHelper.LordUnitySysTypeBySyn(bgName, this.gameObject, typeof(Texture2D)) as Texture2D;
        cuoMat.SetTexture("_FrontTexure", texture);
        smoothMat.SetTexture("_FrontTexure", texture);

        texture = ResHelper.LordUnitySysTypeBySyn(tempName, this.gameObject, typeof(Texture2D)) as Texture2D;
        smoothMat.SetTexture("_BackTexure", texture);

        //texture = Resources.Load<Texture2D>(numName);//AssetDatabase.LoadAssetAtPath<Texture2D>(numName);

        //MeshRenderer num1Renderer = CreateNumGo(numAndhuase[0], Num);
        //num1Renderer.transform.SetParent(transform);
        //num1Renderer.transform.localPosition = new Vector3(Width * 0.5f - NumSize, 0, Height - Height * 0.5f + NumSize);
        //num1Renderer.transform.localEulerAngles = new Vector3(0, 180, 0);
        //num1Renderer.material.SetTexture("_MainTex", texture);

        //MeshRenderer num2Renderer = CreateNumGo(numAndhuase[1], Num);
        //num2Renderer.transform.SetParent(transform);
        //num2Renderer.transform.localPosition = new Vector3(-Width * 0.5f + NumSize, 0, Height + Height * 0.5f - NumSize);
        ////num2Renderer.transform.localEulerAngles = new Vector3(0, 180, 0);
        //num2Renderer.material.SetTexture("_MainTex", texture);

        //texture = Resources.Load<Texture2D>(huaseName);

        //MeshRenderer huase1Renderer = CreateNumGo(numAndhuase[2], huase);
        //huase1Renderer.transform.SetParent(transform);
        //huase1Renderer.transform.localPosition = new Vector3(Width * 0.5f - NumSize, 0, Height - Height * 0.5f + NumSize * 2f);
        //huase1Renderer.transform.localEulerAngles = new Vector3(0, 180, 0);
        //huase1Renderer.material.SetTexture("_MainTex", texture);

        //MeshRenderer huase2Renderer = CreateNumGo(numAndhuase[3], huase);
        //huase2Renderer.transform.SetParent(transform);
        //huase2Renderer.transform.localPosition = new Vector3(-Width * 0.5f + NumSize, 0, Height + Height * 0.5f - NumSize * 2f);
        ////huase2Renderer.transform.localEulerAngles = new Vector3(0, 180, 0);
        //huase2Renderer.material.SetTexture("_MainTex", texture);

        //numMeshRenderer.Add(num1Renderer);
        //numMeshRenderer.Add(num2Renderer);
        //numMeshRenderer.Add(huase1Renderer);
        //numMeshRenderer.Add(huase2Renderer);
    }

    private MeshRenderer CreateNumGo(GameObject obj, Texture Num)
    {
        GameObject num = obj;
        //num.layer = 8;
        MeshRenderer renderer = num.GetComponent<MeshRenderer>();
        MeshFilter filter = num.AddComponent<MeshFilter>();
        float size = NumSize;

        Vector3[] vertices = new Vector3[4];
        Vector2[] uvs = new Vector2[4];
        int[] triangles = new int[6];

        vertices[0] = new Vector3(-size * 0.5f,0,size * 0.5f);
        vertices[1] = new Vector3(size * 0.5f, 0, size * 0.5f);
        vertices[2] = new Vector3(-size * 0.5f, 0, -size * 0.5f);
        vertices[3] = new Vector3(size * 0.5f, 0, -size * 0.5f);

        uvs[0] = new Vector2(0,1);
        uvs[1] = new Vector2(1,1);
        uvs[2] = new Vector2(0,0);
        uvs[3] = new Vector2(1,0);

        triangles[0] = 0;
        triangles[1] = 1;
        triangles[2] = 3;
        triangles[3] = 0;
        triangles[4] = 3;
        triangles[5] = 2;

        Mesh mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.uv = uvs;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        filter.mesh = mesh;

        //renderer.material = new Material(NumMat);
        renderer.material.SetTexture("_MainTex",Num);
        renderer.material.SetFloat("_Alpha",0);
        return renderer;
    }
}
